package map.android.baidu.carpool;

import android.os.Bundle;
import android.view.ViewGroup;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.place.entity.PlaceEntity;
import com.baidu.mapframework.api2.ComAPIManager;
import com.baidu.mapframework.component.comcore.message.ComParams;
import com.baidu.mapframework.component.comcore.message.ComRequest;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.baidu.platform.comapi.map.config.Preferences;
import map.android.baidu.carpool.model.CarpoolPosition;
import map.android.baidu.carpool.page.home.CarpoolHomePage;
import map.android.baidu.carpool.page.home.EntranceInCar;
import map.android.baidu.carpool.page.home.EntranceInRoute;
import map.android.baidu.carpool.page.home.OrderDetailPage;
import map.android.baidu.carpool.page.usercenter.DiscountListPage;
import map.android.baidu.carpool.page.usercenter.OrderListPage;
import map.android.baidu.carpool.preferences.CarpoolSharedPreferences;
import map.android.baidu.carpool.utils.LogUtils;
import map.android.baidu.carpool.utils.UniversalSourceFromParameter;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * The entity of Carpool component
 *
 * @author zhangtongyu
 */
public class CarpoolEntity extends PlaceEntity {

    /*  定义target   实现handleDispatch */
    public static int whichTabCode;
    private String homeName;
    private String homePoint;
    private String companyName;
    private String companyPoint;

    /**
     * 路线页面的Tab类型。0：驾车  1：公交   2：步行
     */
    public static final int VehicleTypeCar = 0;
    public static final int VehicleTypeBus = 1;
    public static final int VehicleTypeFoot = 2;


    /**
     * 基线存储家和公司信息的preference的key，若发现基线改动，需要相应更改key
     */
    public static final String SHORTCUT_HOME_ADDR = "shortcut_home_address";
    public static final String SHORTCUT_HOME_GEO = "shortcut_home_geo";
    public static final String SHORTCUT_COMPANY_ADDR = "shortcut_company_address";
    public static final String SHORTCUT_COMPANY_GEO = "shortcut_company_geo";

    private static final String TELL_CARPOOL_WHICH_TAB = "tell_carpool_which_tab";
    private static final String CARPOOL_MAIN_PAGE = "carpool_main_page";
    private static final String CARPOOL_ORDER_CENTER = "carpool_order_center";
    private static final String LOAD_CARPOOL_VIEW = "load_carpool_view";
    private static final String LOAD_CARPOOL_VIEW_IN_CAR = "load_carpool_view_in_car";
    private static final String CARPOOL_ORDER_DETAIL = "carpool_order_detail";
    private static final String CARPOOL_DISCOUNT_PAGE = "carpool_discount_list";

    private static final String SRC_FROM_NEARBY_RENTCAR = "nearby_rentcar";
    private static final String SRC_FROM_ROUTE_BUS = "route_bus";
    private static final String SRC_FROM_ROUTE_CAR = "route_car";
    private static final String SRC_FROM_ROUTE_FOOT = "route_foot";

    @Override
    public boolean handleDispatch(ComRequest comRequest) {
        super.handleDispatch(comRequest);
        ComParams params = comRequest.getParams();
        saveHomeAndCompanyGeo();
        String target = (String) params.getTargetParameter();
        if(target != null && TELL_CARPOOL_WHICH_TAB.equals(target)){
            whichTabCode = (Integer)params.getBaseParameter("which_tab");
            LogUtils.e("test" , "whichTabCode = " + whichTabCode);
            switch (whichTabCode) {
                case VehicleTypeFoot:
                    initUniversalStatistics(SRC_FROM_ROUTE_FOOT);
                    break;
                case VehicleTypeCar:
                    initUniversalStatistics(SRC_FROM_ROUTE_CAR);
                    break;
                case VehicleTypeBus:
                    initUniversalStatistics(SRC_FROM_ROUTE_BUS);
                    break;
            }

        } else if (target != null && CARPOOL_MAIN_PAGE.equals(target)){
            APIProxy.navi().navigateTo(CarpoolHomePage.class.getName(),null);
        } else if (target != null && CARPOOL_ORDER_CENTER.equals(target)) {
            APIProxy.navi().navigateTo(OrderListPage.class, null);
        } else if (target != null && CARPOOL_ORDER_DETAIL.equals(target)) {
            Bundle bundle = new Bundle();
            String paramsJson = (String) params.getBaseParameter("param");
            String subParams = paramsJson.replaceAll( "\\\\","");
            try {
                JSONObject jsonObject = new JSONObject(subParams);
                String orderId = jsonObject.optString("orderId");
                bundle.putString("orderId", orderId);
                APIProxy.navi().navigateTo(OrderDetailPage.class, bundle);
            } catch (JSONException e) {
                e.printStackTrace();
                APIProxy.navi().navigateTo(CarpoolHomePage.class, null);
            }

        } else if(target != null && CARPOOL_DISCOUNT_PAGE.equals(target)){
                APIProxy.navi().navigateTo(DiscountListPage.class, null);
        } else {
            APIProxy.navi().navigateTo(CarpoolHomePage.class.getName(),null);
        }
        return true;

    }

    @Override
    public Object handleInvoke(ComRequest comRequest) {
        super.handleInvoke(comRequest);
        ComParams params = comRequest.getParams();
        saveHomeAndCompanyGeo();
        String target = (String) params.getTargetParameter();
        if(target != null && LOAD_CARPOOL_VIEW.equals(target)){
            ViewGroup parent = (ViewGroup) params.getBaseParameter("parent_view");
            EntranceInRoute entrance = new EntranceInRoute(APIProxy.res().getBaseActivity(), parent);
        } else if (target != null && CARPOOL_MAIN_PAGE.equals(target)) {
            APIProxy.navi().navigateTo(CarpoolHomePage.class.getName(),null);
        } else if (target != null && LOAD_CARPOOL_VIEW_IN_CAR.equals(target)) {
            ViewGroup parent = (ViewGroup) params.getBaseParameter("parent");
            EntranceInCar entranceInCar = new EntranceInCar(APIProxy.res().getBaseActivity(), parent);
            initUniversalStatistics(SRC_FROM_NEARBY_RENTCAR);
        }
        return true;
    }

    private void initUniversalStatistics(String srcFrom){
        UniversalSourceFromParameter.getInstance().setSrcFrom(srcFrom);
    }

    @Override
    public void doRelease() {
        super.doRelease();
    }

    private void saveHomeAndCompanyGeo(){
        CarpoolPosition mHomeInfoMoc = new CarpoolPosition();
        CarpoolPosition mCompanyInfoMoc = new CarpoolPosition();
        Preferences preferences = Preferences.build(APIProxy.sys().getApplicationContext());
        String companyAddr = preferences.getString(CarpoolEntity.SHORTCUT_COMPANY_ADDR, "");
        String companyGeo = preferences.getString(CarpoolEntity.SHORTCUT_COMPANY_GEO, "");
        String homeAddr = preferences.getString(CarpoolEntity.SHORTCUT_HOME_ADDR, "");
        String homeGeo = preferences.getString(CarpoolEntity.SHORTCUT_HOME_GEO, "");

        GeoPoint companyGeoPtMoc = ComAPIManager.getComAPIManager().getCoordinateApi().getGeoPointFromString(companyGeo);
        GeoPoint homeGeoPtMoc = ComAPIManager.getComAPIManager().getCoordinateApi().getGeoPointFromString(homeGeo);

        mHomeInfoMoc.x = homeGeoPtMoc.getLongitude();
        mHomeInfoMoc.y = homeGeoPtMoc.getLatitude();
        mHomeInfoMoc.address = homeAddr;
        mCompanyInfoMoc.x = companyGeoPtMoc.getLongitude();
        mCompanyInfoMoc.y = companyGeoPtMoc.getLatitude();
        mCompanyInfoMoc.address = companyAddr;

        if(!"".equals(mHomeInfoMoc.address) && mHomeInfoMoc.x != 0.0 && mHomeInfoMoc.y != 0.0){
            CarpoolSharedPreferences.setHomeGeoAddrInfo(APIProxy.res().getBaseActivity(), mHomeInfoMoc);
        }
        if(!"".equals(mCompanyInfoMoc.address) && mCompanyInfoMoc.x != 0.0 && mCompanyInfoMoc.y != 0.0) {
            CarpoolSharedPreferences.setCompanyGeoAddrInfo(APIProxy.res().getBaseActivity(), mCompanyInfoMoc);
        }
    }
}
